package baiqi.sishen.community.controller;

import baiqi.sishen.community.dto.CommentCreateDTO;
import baiqi.sishen.community.dto.CommentDTO;
import baiqi.sishen.community.dto.ResultDTO;
import baiqi.sishen.community.enums.CommentTypeEnum;
import baiqi.sishen.community.execption.CustomizeErrorCode;
import baiqi.sishen.community.execption.CustomizeException;
import baiqi.sishen.community.model.Comment;
import baiqi.sishen.community.model.User;
import baiqi.sishen.community.service.CommentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 兕神
 * @version 1.0
 * DateTime: 2023/5/1
 */
@Controller
public class CommentController {

    @Resource
    private CommentService commentService;

    @ResponseBody
    @PostMapping("/comment")
    public Object comment(
            @RequestBody CommentCreateDTO commentCreateDTO,
            HttpServletRequest request) {

        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            throw new CustomizeException(CustomizeErrorCode.USER_NOT_FOUND);
        }

        //评论内容不得为空
        if (commentCreateDTO == null || StringUtils.isBlank(commentCreateDTO.getContent())) {
            throw new CustomizeException(CustomizeErrorCode.COMMENT_CONTENT_IS_NULL);
        }
        Comment comment = new Comment();
        comment.setCommentator(user.getId());
        comment.setContent(commentCreateDTO.getContent());
        comment.setParentId(commentCreateDTO.getParentId());
        comment.setType(commentCreateDTO.getType());
        comment.setCommentCount(0L);
        comment.setLikeCount(0L);

        commentService.insert(comment,user);
        //返回成功码
        return ResultDTO.success();
    }

    /**
     * 二级评论的数据回显
     * @param id 父评论id
     * @return ResultDTO
     */
    @ResponseBody
    @GetMapping("/comment/{id}")
    public ResultDTO<List<CommentDTO>> comment2(@PathVariable("id") Long id) {

        List<CommentDTO> comments = commentService.getCommentsByParentId(id, CommentTypeEnum.COMMENT);
        return ResultDTO.success(comments);
    }
}
